using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;

namespace MouseKeyboardOperationSimulator
{
    /// <summary>
    /// 内置主题类型枚举
    /// </summary>
    public enum BuiltInTheme
    {
        Default,
        Light,
        Dark
    }
    
    // Windows API 声明用于设置标题栏颜色
    internal class NativeMethods
    {
        [DllImport("dwmapi.dll")]
        public static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize);
        
        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
        
        public const int DWMWA_CAPTION_COLOR = 35;  // Windows 10+ (Build 18985+)
        public const int DWMWA_TEXT_COLOR = 36;     // Windows 10+ (Build 18985+)
    }
    
    /// <summary>
    /// 主题管理器类，用于加载和应用界面主题
    /// </summary>
    public class ThemeManager
    {
        private JObject _themeConfig;
        private Dictionary<string, Color> _colorPalette;
        private string _themeFilePath;

        /// <summary>
        /// 构造函数（从文件加载主题）
        /// </summary>
        /// <param name="themeFilePath">主题配置文件路径</param>
        public ThemeManager(string themeFilePath = "themes/theme.json")
        {
            _themeFilePath = themeFilePath;
            LoadTheme();
        }

        /// <summary>
        /// 构造函数（使用内置主题）
        /// </summary>
        /// <param name="builtInTheme">内置主题类型</param>
        public ThemeManager(BuiltInTheme builtInTheme)
        {
            LoadBuiltInTheme(builtInTheme);
        }

        /// <summary>
        /// 加载主题配置
        /// </summary>
        private void LoadTheme()
        {
            try
            {
                if (File.Exists(_themeFilePath))
                {
                    string jsonContent = File.ReadAllText(_themeFilePath);
                    _themeConfig = JObject.Parse(jsonContent);
                    InitializeColorPalette();
                }
                else
                {
                    // 如果主题文件不存在，加载默认内置主题
                    LoadBuiltInTheme(BuiltInTheme.Default);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载主题配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LoadBuiltInTheme(BuiltInTheme.Default);
            }
        }

        /// <summary>
        /// 加载内置主题
        /// </summary>
        /// <param name="builtInTheme">内置主题类型</param>
        private void LoadBuiltInTheme(BuiltInTheme builtInTheme)
        {
            try
            {
                string jsonContent = GetBuiltInThemeJson(builtInTheme);
                _themeConfig = JObject.Parse(jsonContent);
                InitializeColorPalette();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载内置主题失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                CreateDefaultTheme();
            }
        }

        /// <summary>
        /// 获取内置主题的JSON内容
        /// </summary>
        /// <param name="builtInTheme">内置主题类型</param>
        /// <returns>主题JSON字符串</returns>
        private string GetBuiltInThemeJson(BuiltInTheme builtInTheme)
        {
            // 首先尝试从文件系统加载（保持向后兼容性）
            string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
            string themesDirectory = Path.Combine(appDirectory, "themes");
            
            try
            {
                switch (builtInTheme)
                {
                    case BuiltInTheme.Default:
                        string defaultThemePath = Path.Combine(themesDirectory, "theme.json");
                        if (File.Exists(defaultThemePath))
                        {
                            return File.ReadAllText(defaultThemePath, Encoding.UTF8);
                        }
                        break;
                    case BuiltInTheme.Light:
                        string lightThemePath = Path.Combine(themesDirectory, "light_theme.json");
                        if (File.Exists(lightThemePath))
                        {
                            return File.ReadAllText(lightThemePath, Encoding.UTF8);
                        }
                        break;
                    case BuiltInTheme.Dark:
                        string darkThemePath = Path.Combine(themesDirectory, "dark_theme.json");
                        if (File.Exists(darkThemePath))
                        {
                            return File.ReadAllText(darkThemePath, Encoding.UTF8);
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                // 如果从文件系统加载失败，继续尝试从嵌入资源加载
                System.Diagnostics.Debug.WriteLine($"从文件系统加载主题失败: {ex.Message}");
            }
            
            // 如果文件系统中没有找到主题文件，则从嵌入资源加载
            try
            {
                string resourceName = "";
                switch (builtInTheme)
                {
                    case BuiltInTheme.Default:
                        resourceName = "MouseKeyboardOperationSimulator.themes.theme.json";
                        break;
                    case BuiltInTheme.Light:
                        resourceName = "MouseKeyboardOperationSimulator.themes.light_theme.json";
                        break;
                    case BuiltInTheme.Dark:
                        resourceName = "MouseKeyboardOperationSimulator.themes.dark_theme.json";
                        break;
                    default:
                        resourceName = "MouseKeyboardOperationSimulator.themes.theme.json";
                        break;
                }
                
                using (var stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                {
                    if (stream != null)
                    {
                        using (var reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // 如果从嵌入资源加载也失败，则返回默认主题的硬编码内容
                MessageBox.Show($"无法从嵌入资源加载主题: {ex.Message}\n将使用默认主题。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            
            // 创建默认主题配置
            CreateDefaultTheme();
            
            // 将JObject转换为JSON字符串并返回
            return _themeConfig.ToString();
        }

        /// <summary>
        /// 创建默认主题
        /// </summary>
        private void CreateDefaultTheme()
        {
            _themeConfig = new JObject
            {
                ["name"] = "默认主题",
                ["author"] = "luzhishen666",
                ["version"] = "1.0"
            };

            var colors = new JObject
            {
                ["primary"] = "#2196F3",
                ["secondary"] = "#FF5722",
                ["success"] = "#4CAF50",
                ["warning"] = "#FFC107",
                ["danger"] = "#F44336",
                ["info"] = "#00BCD4",
                ["light"] = "#F5F5F5",
                ["dark"] = "#333333",
                ["background"] = "#FFFFFF",
                ["textPrimary"] = "#212121",
                ["textSecondary"] = "#757575",
                ["border"] = "#BDBDBD"
            };

            _themeConfig["colors"] = colors;
            
            // 添加默认样式配置
            var styles = new JObject
            {
                ["form"] = new JObject
                {
                    ["backgroundColor"] = "background",
                    ["foregroundColor"] = "textPrimary"
                },
                ["button"] = new JObject
                {
                    ["backgroundColor"] = "primary",
                    ["foregroundColor"] = "#FFFFFF",
                    ["borderColor"] = "primary",
                    ["hoverBackgroundColor"] = "#1976D2",
                    ["hoverForegroundColor"] = "#FFFFFF"
                },
                ["dataGridView"] = new JObject
                {
                    ["backgroundColor"] = "background",
                    ["foregroundColor"] = "textPrimary",
                    ["headerBackgroundColor"] = "primary",
                    ["headerForegroundColor"] = "#FFFFFF",
                    ["selectionBackgroundColor"] = "secondary",
                    ["selectionForegroundColor"] = "#FFFFFF",
                    ["gridColor"] = "border"
                },
                ["groupBox"] = new JObject
                {
                    ["backgroundColor"] = "background",
                    ["foregroundColor"] = "textPrimary",
                    ["borderColor"] = "border"
                },
                ["label"] = new JObject
                {
                    ["backgroundColor"] = "background",
                    ["foregroundColor"] = "textPrimary"
                }
            };
            
            _themeConfig["styles"] = styles;
            InitializeColorPalette();
        }

        /// <summary>
        /// 初始化颜色调色板
        /// </summary>
        private void InitializeColorPalette()
        {
            _colorPalette = new Dictionary<string, Color>();
            
            if (_themeConfig["colors"] != null)
            {
                foreach (JProperty color in _themeConfig["colors"])
                {
                    string colorName = color.Name;
                    string colorValue = color.Value.ToString();
                    _colorPalette[colorName] = ColorTranslator.FromHtml(colorValue);
                }
            }
        }

        /// <summary>
        /// 获取颜色
        /// </summary>
        /// <param name="colorName">颜色名称</param>
        /// <returns>颜色对象</returns>
        public Color GetColor(string colorName)
        {
            if (_colorPalette.ContainsKey(colorName))
            {
                return _colorPalette[colorName];
            }
            return Color.Black; // 默认返回黑色
        }

        /// <summary>
        /// 应用主题到窗体
        /// </summary>
        /// <param name="form">目标窗体</param>
        public void ApplyTheme(Form form)
        {
            if (_themeConfig["styles"]?["form"] != null)
            {
                var formStyle = _themeConfig["styles"]["form"];
                form.BackColor = GetColor(formStyle["backgroundColor"].ToString());
                form.ForeColor = GetColor(formStyle["foregroundColor"].ToString());
                
                // 应用标题栏颜色（如果配置中存在）
                ApplyTitleBarColors(form, formStyle);
            }

            ApplyThemeToControls(form.Controls);
        }
        
        /// <summary>
        /// 检查当前Windows版本是否支持DWMWA_CAPTION_COLOR
        /// </summary>
        /// <returns>如果支持返回true，否则返回false</returns>
        private bool IsCaptionColorSupported()
        {
            try
            {
                var osVersion = Environment.OSVersion.Version;
                // DWMWA_CAPTION_COLOR 需要 Windows 10 Build 18985 或更高版本
                // Windows 10 版本 2004 (20H1) 的内部版本号是 19041
                // 您的系统是 Windows 10 Pro 版本 2009，内部版本号 19043，应该支持此功能
                return osVersion.Build >= 18985;
            }
            catch
            {
                // 如果无法确定版本，默认返回true并在实际调用时处理错误
                return true;
            }
        }

        /// <summary>
        /// 应用标题栏颜色
        /// </summary>
        /// <param name="form">目标窗体</param>
        /// <param name="formStyle">窗体样式配置</param>
        private void ApplyTitleBarColors(Form form, JToken formStyle)
        {
            // 检查当前系统是否支持标题栏颜色设置
            bool isSupported = IsCaptionColorSupported();
            System.Diagnostics.Debug.WriteLine($"IsCaptionColorSupported: {isSupported}");
            
            if (!isSupported)
            {
                System.Diagnostics.Debug.WriteLine("当前Windows版本不支持标题栏颜色设置");
                return;
            }

            try
            {
                bool colorApplied = false;
                
                // 检查是否配置了标题栏颜色
                if (formStyle["titleBarColor"] != null)
                {
                    Color titleBarColor = GetColor(formStyle["titleBarColor"].ToString());
                    System.Diagnostics.Debug.WriteLine($"Title bar color from theme: {titleBarColor}");
                    // 将Color转换为int（0xAABBGGRR格式）
                    int captionColorValue = (titleBarColor.B << 16) | (titleBarColor.G << 8) | titleBarColor.R | (titleBarColor.A << 24);
                    System.Diagnostics.Debug.WriteLine($"Caption color value: {captionColorValue:X8}");
                    
                    // 设置标题栏背景色
                    int result = NativeMethods.DwmSetWindowAttribute(form.Handle, NativeMethods.DWMWA_CAPTION_COLOR, ref captionColorValue, sizeof(int));
                    System.Diagnostics.Debug.WriteLine($"DwmSetWindowAttribute (Caption Color) result: {result}");
                    colorApplied = true;
                }
                
                // 检查是否配置了标题栏文字颜色
                if (formStyle["titleBarTextColor"] != null)
                {
                    Color titleBarTextColor = GetColor(formStyle["titleBarTextColor"].ToString());
                    System.Diagnostics.Debug.WriteLine($"Title bar text color from theme: {titleBarTextColor}");
                    // 将Color转换为int（0xAABBGGRR格式）
                    int textColorValue = (titleBarTextColor.B << 16) | (titleBarTextColor.G << 8) | titleBarTextColor.R | (titleBarTextColor.A << 24);
                    System.Diagnostics.Debug.WriteLine($"Text color value: {textColorValue:X8}");
                    
                    // 设置标题栏文字色
                    int result = NativeMethods.DwmSetWindowAttribute(form.Handle, NativeMethods.DWMWA_TEXT_COLOR, ref textColorValue, sizeof(int));
                    System.Diagnostics.Debug.WriteLine($"DwmSetWindowAttribute (Text Color) result: {result}");
                    colorApplied = true;
                }
                
                // 如果应用了颜色，则刷新窗体以使更改生效
                if (colorApplied)
                {
                    System.Diagnostics.Debug.WriteLine("Applying refresh methods to make title bar color changes visible");
                    // 强制窗体重绘
                    form.Invalidate();
                    form.Update();
                    
                    // 发送消息以刷新非客户区
                    const int WM_NCPAINT = 0x85;
                    NativeMethods.SendMessage(form.Handle, WM_NCPAINT, IntPtr.Zero, IntPtr.Zero);
                    
                    // 尝试其他方式强制刷新标题栏
                    form.Text += " ";  // 临时修改标题
                    form.Text = form.Text.TrimEnd();  // 恢复标题
                    System.Diagnostics.Debug.WriteLine("Refresh methods applied");
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("No title bar colors were applied - colorApplied is false");
                }
            }
            catch (Exception ex)
            {
                // 忽略标题栏颜色设置的错误，因为这可能在某些Windows版本上不支持
                System.Diagnostics.Debug.WriteLine($"设置标题栏颜色时出错: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"Exception stack trace: {ex.StackTrace}");
            }
        }

        /// <summary>
        /// 递归应用主题到控件
        /// </summary>
        /// <param name="controls">控件集合</param>
        private void ApplyThemeToControls(Control.ControlCollection controls)
        {
            foreach (Control control in controls)
            {
                ApplyThemeToControl(control);
                
                // 递归处理子控件
                if (control.HasChildren)
                {
                    ApplyThemeToControls(control.Controls);
                }
            }
        }

        /// <summary>
        /// 应用主题到单个控件
        /// </summary>
        /// <param name="control">控件</param>
        private void ApplyThemeToControl(Control control)
        {
            string controlType = control.GetType().Name.ToLower();

            switch (controlType)
            {
                case "button":
                case "buttonbase":
                    ApplyButtonStyle(control as Button);
                    break;
                case "datagridview":
                    ApplyDataGridViewStyle(control as DataGridView);
                    break;
                case "groupbox":
                    ApplyGroupBoxStyle(control as GroupBox);
                    break;
                case "label":
                    ApplyLabelStyle(control as Label);
                    break;
                case "checkbox":
                    ApplyCheckBoxStyle(control as CheckBox);
                    break;
                case "radiobutton":
                    ApplyRadioButtonStyle(control as RadioButton);
                    break;
                case "textbox":
                    ApplyTextBoxStyle(control as TextBox);
                    break;
                case "panel":
                    ApplyPanelStyle(control as Panel);
                    break;
                case "datagridviewcomboboxcell":
                    // DataGridViewComboBoxCell 的样式会在 DataGridView 中处理
                    break;
            }
        }

        /// <summary>
        /// 应用按钮样式
        /// </summary>
        /// <param name="button">按钮控件</param>
        private void ApplyButtonStyle(Button button)
        {
            if (button == null || _themeConfig["styles"]?["button"] == null) return;

            var buttonStyle = _themeConfig["styles"]["button"];
            button.BackColor = GetColor(buttonStyle["backgroundColor"].ToString());
            button.ForeColor = GetColor(buttonStyle["foregroundColor"].ToString());
            button.FlatStyle = FlatStyle.Flat;
            button.FlatAppearance.BorderColor = GetColor(buttonStyle["borderColor"].ToString());
            button.FlatAppearance.BorderSize = 1;
            
            // 添加悬停效果
            button.MouseEnter += (sender, e) => {
                button.BackColor = GetColor(buttonStyle["hoverBackgroundColor"].ToString());
                button.ForeColor = GetColor(buttonStyle["hoverForegroundColor"].ToString());
            };
            
            button.MouseLeave += (sender, e) => {
                button.BackColor = GetColor(buttonStyle["backgroundColor"].ToString());
                button.ForeColor = GetColor(buttonStyle["foregroundColor"].ToString());
            };
        }

        /// <summary>
        /// 应用DataGridView样式
        /// </summary>
        /// <param name="dataGridView">DataGridView控件</param>
        private void ApplyDataGridViewStyle(DataGridView dataGridView)
        {
            if (dataGridView == null || _themeConfig["styles"]?["dataGridView"] == null) return;

            var gridStyle = _themeConfig["styles"]["dataGridView"];
            
            // 设置背景色和前景色
            dataGridView.BackgroundColor = GetColor(gridStyle["backgroundColor"].ToString());
            dataGridView.ForeColor = GetColor(gridStyle["foregroundColor"].ToString());
            
            // 设置网格线颜色
            dataGridView.GridColor = GetColor(gridStyle["gridColor"].ToString());
            
            // 设置选中行的颜色
            dataGridView.DefaultCellStyle.SelectionBackColor = GetColor(gridStyle["selectionBackgroundColor"].ToString());
            dataGridView.DefaultCellStyle.SelectionForeColor = GetColor(gridStyle["selectionForegroundColor"].ToString());
            
            // 设置表头样式
            dataGridView.EnableHeadersVisualStyles = false;
            dataGridView.ColumnHeadersDefaultCellStyle.BackColor = GetColor(gridStyle["headerBackgroundColor"].ToString());
            dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = GetColor(gridStyle["headerForegroundColor"].ToString());
            dataGridView.ColumnHeadersDefaultCellStyle.SelectionBackColor = GetColor(gridStyle["headerBackgroundColor"].ToString());
            
            // 设置边框样式
            dataGridView.BorderStyle = BorderStyle.FixedSingle;
            dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            dataGridView.RowHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
            dataGridView.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single;
        }

        /// <summary>
        /// 应用GroupBox样式
        /// </summary>
        /// <param name="groupBox">GroupBox控件</param>
        private void ApplyGroupBoxStyle(GroupBox groupBox)
        {
            if (groupBox == null || _themeConfig["styles"]?["groupBox"] == null) return;

            var groupBoxStyle = _themeConfig["styles"]["groupBox"];
            groupBox.BackColor = GetColor(groupBoxStyle["backgroundColor"].ToString());
            groupBox.ForeColor = GetColor(groupBoxStyle["foregroundColor"].ToString());
            groupBox.FlatStyle = FlatStyle.Flat;
        }

        /// <summary>
        /// 应用Label样式
        /// </summary>
        /// <param name="label">Label控件</param>
        private void ApplyLabelStyle(Label label)
        {
            if (label == null || _themeConfig["styles"]?["label"] == null) return;

            var labelStyle = _themeConfig["styles"]["label"];
            label.BackColor = GetColor(labelStyle["backgroundColor"].ToString());
            label.ForeColor = GetColor(labelStyle["foregroundColor"].ToString());
        }

        /// <summary>
        /// 应用CheckBox样式
        /// </summary>
        /// <param name="checkBox">CheckBox控件</param>
        private void ApplyCheckBoxStyle(CheckBox checkBox)
        {
            if (checkBox == null || _themeConfig["styles"]?["checkbox"] == null) return;

            var checkBoxStyle = _themeConfig["styles"]["checkbox"];
            checkBox.BackColor = GetColor(checkBoxStyle["backgroundColor"].ToString());
            checkBox.ForeColor = GetColor(checkBoxStyle["foregroundColor"].ToString());
        }

        /// <summary>
        /// 应用RadioButton样式
        /// </summary>
        /// <param name="radioButton">RadioButton控件</param>
        private void ApplyRadioButtonStyle(RadioButton radioButton)
        {
            if (radioButton == null || _themeConfig["styles"]?["radiobutton"] == null) return;

            var radioButtonStyle = _themeConfig["styles"]["radiobutton"];
            radioButton.BackColor = GetColor(radioButtonStyle["backgroundColor"].ToString());
            radioButton.ForeColor = GetColor(radioButtonStyle["foregroundColor"].ToString());
        }

        /// <summary>
        /// 应用TextBox样式
        /// </summary>
        /// <param name="textBox">TextBox控件</param>
        private void ApplyTextBoxStyle(TextBox textBox)
        {
            if (textBox == null || _themeConfig["styles"]?["textbox"] == null) return;

            var textBoxStyle = _themeConfig["styles"]["textbox"];
            textBox.BackColor = GetColor(textBoxStyle["backgroundColor"].ToString());
            textBox.ForeColor = GetColor(textBoxStyle["foregroundColor"].ToString());
            textBox.BorderStyle = BorderStyle.FixedSingle;
        }

        /// <summary>
        /// 应用Panel样式
        /// </summary>
        /// <param name="panel">Panel控件</param>
        private void ApplyPanelStyle(Panel panel)
        {
            if (panel == null || _themeConfig["styles"]?["panel"] == null) return;

            var panelStyle = _themeConfig["styles"]["panel"];
            panel.BackColor = GetColor(panelStyle["backgroundColor"].ToString());
            panel.ForeColor = GetColor(panelStyle["foregroundColor"].ToString());
            panel.BorderStyle = BorderStyle.FixedSingle;
        }

        /// <summary>
        /// 重新加载主题
        /// </summary>
        public void ReloadTheme()
        {
            LoadTheme();
        }
    }
}